package wyd

import java.io.IOException

import javax.servlet.Filter
import javax.servlet.FilterChain
import javax.servlet.FilterConfig
import javax.servlet.RequestDispatcher
import javax.servlet.ServletContext
import javax.servlet.ServletException
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

import org.slf4j.Logger
import org.slf4j.LoggerFactory

public class WydServletFilter implements Filter {

	private static final long serialVersionUID = 1L

	final Logger _log = LoggerFactory.getLogger(WydServletFilter.class)

	final List<String> publicUrls = [
		'/echo.groovy',
		'/wydEcho.groovy',
		'/about.groovy',
		'/wydAbout.groovy',
		'/wydIndex.groovy',
		'/login.groovy',
		'/wydLogin.groovy',
		'/acmAuthenticate.groovy',
		'/logout.groovy',
		'/wydLogout.groovy',
		'/mobile/wydLogin.groovy',
		'/mobile/acmAuthenticate.groovy',
		'/mobile/wydLogout.groovy',
		'/mobile/wydAbout.groovy',
		'/a/init.groovy'
	]

	protected FilterConfig filterConfig

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig
	}

	@Override
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
	FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request
		def msg = req.getParameter('infoMessage')
		if (msg != null) {
			req.setAttribute('infoMessage', msg)
		}
		if(_log.isDebugEnabled()) {
			_log.debug('Info Message = {}', msg)
		}

		msg = req.getParameter('errorMessage')
		if (msg != null) {
			req.setAttribute('errorMessage', msg)
		}
		if(_log.isDebugEnabled()) {
			_log.debug('Error Message = {}', msg)
		}

		def backUrl = req.getParameter('backUrl')
		if (backUrl != null) {
			request.setAttribute('backUrl', backUrl)
			if (_log.isDebugEnabled()) {
				_log.debug('Back URL = {}', backUrl)
			}
		}
		HttpSession session = req.getSession(true)
		def user = session.getAttribute('user')
		if(!publicUrls.contains(req.getRequestURI()) && !req.getRequestURI().startsWith('/t/') && user == null) {
			String s = req.getRequestURI().startsWith('/mobile') ? '/mobile/wydLogin.groovy' : '/wydLogin.groovy'
			ServletContext scontext = this.filterConfig.getServletContext()
			RequestDispatcher rd = scontext.getRequestDispatcher(s)
			s = "Please login to access this page '$request.requestURI'"
			request.setAttribute('errorMessage', s)
			rd.forward(request, response);
			return
		}
		chain.doFilter(request, response)
	}
}
